/**
 * parser.js 主要功能
 * 将es6转为es5，将代码转为ast
 * 分析依赖
 */

const fs = require('fs');
const babylon = require('babylon');
const traverse = require('babel-traverse').default;
const { transformFromAst } = require('babel-core');

module.exports = {
  // 接收一个路径，将内容转换为AST
  getAST: (path) => {
    const source = fs.readFileSync(path, 'utf-8');
    
    return babylon.parse(source, {
      sourceType: 'module',
    })
  },

  getDependencies: (ast) => {
    const dependencies = [];

    traverse(ast, {
      // 怎么处理Import语句
      ImportDeclaration: ({ node }) => {
        // 获取节点的依赖
        dependencies.push(node.source.value);
      }
    })

    return dependencies;
  },

  // 将AST转为源码
  transform: (ast) => {
    const { code } = transformFromAst(ast, null, {
      // ES6的代码都能解析
      presets: ['env'],
    });

    return code;
  }
}